
import { Connection } from "./connection";
/**
 * 事务类
 */
export class mysqlTransaction {

    /**
     * 事务对应的连接对象
     */
    connection: Connection

    /**
    * @param conn 连接对象
    */
    constructor(conn:Connection) { 
        this.connection = conn
    }

    /**
     * 实际开始事务
     */
    async  begin() {
        await new Promise((resolve, reject) => {
            this.connection.conn.beginTransaction((err) => {
                if (err) {
                    return reject(err);
                }
                resolve(null);
            });
        });
    }

    /**
     * 实际事务提交
     */
    async commit() {
        await new Promise((resolve, reject) => {
            this.connection.conn.commit(async (err) => {
                if (err) {
                    await this.rollback();
                    return reject(err);
                }
                resolve(null);
            });
        });
    }

    /**
     * 实际事务回滚
     */
    async rollback() {
        await new Promise((resolve, reject) => {
            this.connection.conn.rollback((err) => {
                if (err) {
                    return reject(err);
                }
                resolve(null);
            });
        });
    }

    /**
     * 创建保存点
     * @param savepointName 保存点名称
     */
    async createSavepoint(savepointName) {
        await new Promise((resolve, reject) => {
            this.connection.conn.query(`SAVEPOINT ${savepointName}`, (err) => {
                if (err) {
                    return reject(err);
                }
                resolve(null);
            });
        });
    }

    /**
     * 释放保存点
     * @param savepointName 
     */
    async releaseSavepoint(savepointName) {
        await new Promise((resolve, reject) => {
            this.connection.conn.query(`RELEASE SAVEPOINT ${savepointName}`, (err) => {
                if (err) {
                    return reject(err);
                }
                resolve(null);
            });
        });
    }

    /**
     * 回滚到保存点
     * @param savepointName 保存点名称
     */
    async rollbackToSavepoint(savepointName) {
        await new Promise((resolve, reject) => {
            this.connection.conn.query(`ROLLBACK TO SAVEPOINT ${savepointName}`, (err) => {
                if (err) {
                    return reject(err);
                }
                resolve(null);
            });
        });
    }
}
